package com.seleniti.enpareja.web.desktop.server.model.integration.service.impl.appengine;

import java.util.List;

import org.apache.log4j.Logger;
import org.ioc.commons.utils.jdo.JdoQueryHelper;

import com.seleniti.enpareja.controller.common.domain.Page;
import com.seleniti.enpareja.controller.common.exception.EnParejaException;
import com.seleniti.enpareja.controller.model.integration.database.domain.Couple;
import com.seleniti.enpareja.controller.model.integration.database.domain.HomeTask;

public class GAEHomeTaskService extends GAEService {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(GAEHomeTaskService.class);

	public GAEHomeTaskService() {
		logger.info("GAE Couple service instance");
	}

	public HomeTask find(String id) {
		return pm.getObjectById(HomeTask.class, id);
	}

	public void save(HomeTask ht) throws EnParejaException {
		pm.makePersistent(ht);
	}

	public void delete(HomeTask ht) throws EnParejaException {
		pm.deletePersistent(ht);
	}

	public Page<HomeTask> getPage(long start, long length) {

		Page<HomeTask> page = new Page<HomeTask>();

			JdoQueryHelper qh = JdoQueryHelper.newQuery(pm, HomeTask.class);

			addLoggedUserCoupleFilter(qh);
			
			qh.setResult("count(this)");
			Long total = (Long) qh.execute();

			qh.setRange(start, start + length);
			qh.setResult("this");

			List<HomeTask> users = (List<HomeTask>) qh.execute();

			page.setTotal(total != null ? total.longValue() : 0l);
			page.setElements(users);

		return page;

	}

	public HomeTask createTask(String coupleId) {
		logger.info("Creating task for couple " + coupleId);
		HomeTask ht = new HomeTask();

		Couple couple = pm.getObjectById(Couple.class, coupleId);

		ht.setCouple(couple);

		couple.getHomeTasks().add(ht);

		// pm.makePersistent(ht);

		return ht;
	}
}
